<template>
  <div class="profile-container agri-page-container">
    <div class="page-header agri-page-header">
      <div class="page-title agri-page-title">
        <el-icon><User /></el-icon>
        <span>个人中心</span>
      </div>
    </div>
    
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="8" :lg="6">
        <!-- 用户卡片 -->
        <el-card class="user-card agri-card">
          <div class="user-card-header">
            <div class="avatar-container">
              <el-avatar :size="100" src="/avatar.png">
                {{ userInfo.nickname ? userInfo.nickname.substring(0, 1) : 'U' }}
              </el-avatar>
            </div>
            <h2 class="user-name">{{ userInfo.nickname }}</h2>
            <p class="user-role">{{ getRoleLabel(userInfo.role) }}</p>
          </div>
          
          <div class="user-card-content">
            <div class="user-info-item">
              <el-icon><User /></el-icon>
              <span>{{ userInfo.username }}</span>
            </div>
            <div class="user-info-item">
              <el-icon><Phone /></el-icon>
              <span>{{ userInfo.phone || '未设置' }}</span>
            </div>
            <div class="user-info-item">
              <el-icon><Message /></el-icon>
              <span>{{ userInfo.email || '未设置' }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="24" :md="16" :lg="18">
        <!-- 主要内容 -->
        <el-card class="main-card agri-card">
          <div class="agri-tabs-wrapper">
            <el-tabs v-model="activeName">
              <el-tab-pane label="用户信息" name="userInfo">
                <el-form
                  ref="userFormRef"
                  :model="userForm"
                  :rules="userRules"
                  label-width="120px"
                  v-loading="loading.userInfo"
                >
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="userForm.username" disabled />
                  </el-form-item>
                  
                  <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="userForm.nickname" />
                  </el-form-item>
                  
                  <el-form-item label="手机号" prop="phone">
                    <el-input v-model="userForm.phone" />
                  </el-form-item>
                  
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="userForm.email" />
                  </el-form-item>
                  
                  <el-form-item>
                    <el-button type="primary" @click="submitUserForm" :loading="submitLoading">
                      保存修改
                    </el-button>
                    <el-button @click="resetUserForm">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
              
              <el-tab-pane label="账号安全" name="security">
                <el-form
                  ref="passwordFormRef"
                  :model="passwordForm"
                  :rules="passwordRules"
                  label-width="120px"
                  v-loading="loading.password"
                >
                  <el-form-item label="当前密码" prop="currentPassword">
                    <el-input
                      v-model="passwordForm.currentPassword"
                      type="password"
                      show-password
                      autocomplete="new-password"
                    />
                  </el-form-item>
                  
                  <el-form-item label="新密码" prop="newPassword">
                    <el-input
                      v-model="passwordForm.newPassword"
                      type="password"
                      show-password
                      autocomplete="new-password"
                    />
                  </el-form-item>
                  
                  <el-form-item label="确认新密码" prop="confirmPassword">
                    <el-input
                      v-model="passwordForm.confirmPassword"
                      type="password"
                      show-password
                      autocomplete="new-password"
                    />
                  </el-form-item>
                  
                  <el-form-item>
                    <el-button type="primary" @click="submitPasswordForm" :loading="passwordLoading">
                      修改密码
                    </el-button>
                    <el-button @click="resetPasswordForm">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
              
            </el-tabs>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 对话框 -->
    <div class="agri-dialog-wrapper">
      <el-dialog
        v-model="passwordDialogVisible"
        title="修改密码"
        width="500px"
      >
        <el-form
          ref="changePasswordFormRef"
          :model="changePasswordForm"
          :rules="changePasswordRules"
          label-width="120px"
        >
          <el-form-item label="当前密码" prop="currentPassword">
            <el-input
              v-model="changePasswordForm.currentPassword"
              type="password"
              show-password
              autocomplete="new-password"
            />
          </el-form-item>
          
          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="changePasswordForm.newPassword"
              type="password"
              show-password
              autocomplete="new-password"
            />
          </el-form-item>
          
          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input
              v-model="changePasswordForm.confirmPassword"
              type="password"
              show-password
              autocomplete="new-password"
            />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="passwordDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="updatePassword" :loading="updatePasswordLoading">
              确认修改
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useUserStore } from '../../store';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  User, Edit, Phone, Message, Location, Calendar, Lock 
} from '@element-plus/icons-vue';
import { format } from 'date-fns';
import { getUserInfo, updateUserInfo, changePassword } from '../../api/user';

// 状态和仓库
const userStore = useUserStore();
const activeName = ref('userInfo');
const passwordDialogVisible = ref(false);

// 表单引用
const userFormRef = ref(null);
const passwordFormRef = ref(null);

// 加载状态
const loading = reactive({
  userInfo: false,
  password: false,
  settings: false
});
const submitLoading = ref(false);
const passwordLoading = ref(false);
const settingsLoading = ref(false);

// 用户信息
const userInfo = computed(() => userStore.userInfo);
const userAvatar = computed(() => userInfo.value.avatar || '');

// 主题设置
const themeSettings = reactive({
  mode: 'light' // light, dark, system
});

// 通知设置
const notificationSettings = reactive({
  email: true,
  system: true
});

// 显示设置
const displaySettings = reactive({
  checkedFeatures: ['welcomeMessage', 'quickActions']
});

// 用户信息表单
const userForm = reactive({
  username: '',
  nickname: '',
  phone: '',
  email: '',
  address: '',
  bio: ''
});

// 密码表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 用户表单验证规则
const userRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的电子邮箱地址', trigger: 'blur' }
  ]
};

// 密码表单验证规则
const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return '未知';
  return format(new Date(date), 'yyyy-MM-dd');
};

// 获取角色标签
const getRoleLabel = (role) => {
  const roles = {
    admin: '系统管理员',
    farmer: '农户',
    buyer: '农产品买家',
    seller: '肥料卖家'
  };
  return roles[role] || '普通用户';
};

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!');
    return false;
  }
  return true;
};

// 处理头像上传
const handleAvatarUpload = (options) => {
  const { file } = options;
  
  // 实际项目应调用上传 API
  // 这里使用 FileReader 模拟上传
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    // 调用修改用户信息 API 更新头像
    updateUserAvatar(reader.result);
  };
};

// 更新用户头像
const updateUserAvatar = async (avatarData) => {
  try {
    await userStore.updateUser({
      avatar: avatarData
    });
    ElMessage.success('头像更新成功');
  } catch (error) {
    console.error('头像上传失败', error);
    ElMessage.error('头像上传失败');
  }
};

// 提交用户信息表单
const submitUserForm = async () => {
  if (!userFormRef.value) return;
  
  await userFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    try {
      submitLoading.value = true;
      await userStore.updateUser(userForm);
      ElMessage.success('个人信息更新成功');
    } catch (error) {
      console.error('更新失败', error);
      ElMessage.error('个人信息更新失败: ' + (error.message || '未知错误'));
    } finally {
      submitLoading.value = false;
    }
  });
};

// 重置用户信息表单
const resetUserForm = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields();
  }
  initUserForm();
};

// 提交修改密码表单
const submitPasswordForm = async () => {
  if (!passwordFormRef.value) return;
  
  await passwordFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    try {
      passwordLoading.value = true;
      await userStore.updatePassword({
        oldPassword: passwordForm.currentPassword,
        newPassword: passwordForm.newPassword
      });
      ElMessage.success('密码修改成功，请重新登录');
      resetPasswordForm();
    } catch (error) {
      console.error('密码修改失败', error);
      ElMessage.error('密码修改失败: ' + (error.message || '未知错误'));
    } finally {
      passwordLoading.value = false;
    }
  });
};

// 重置密码表单
const resetPasswordForm = () => {
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields();
  }
  Object.assign(passwordForm, {
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  });
};

// 改变主题
const changeTheme = (mode) => {
  // 实现改变主题的逻辑
};

// 保存设置
const saveSettings = async () => {
  try {
    settingsLoading.value = true;
    
    // 实际项目应调用 API 保存用户设置
    // 这里简单模拟
    localStorage.setItem('themeSettings', JSON.stringify(themeSettings));
    localStorage.setItem('notificationSettings', JSON.stringify(notificationSettings));
    localStorage.setItem('displaySettings', JSON.stringify(displaySettings));
    
    ElMessage.success('设置保存成功');
  } catch (error) {
    console.error('保存设置失败', error);
    ElMessage.error('保存设置失败');
  } finally {
    settingsLoading.value = false;
  }
};

// 重置设置
const resetSettings = () => {
  Object.assign(themeSettings, { mode: 'light' });
  Object.assign(notificationSettings, { email: true, system: true });
  Object.assign(displaySettings, { checkedFeatures: ['welcomeMessage', 'quickActions'] });
  
  changeTheme('light');
};

// 初始化用户表单
const initUserForm = () => {
  Object.assign(userForm, {
    username: userInfo.value.username || '',
    nickname: userInfo.value.nickname || '',
    phone: userInfo.value.phone || '',
    email: userInfo.value.email || '',
    address: userInfo.value.address || '',
    bio: userInfo.value.bio || ''
  });
};

// 加载用户设置
const loadUserSettings = () => {
  try {
    const savedThemeSettings = localStorage.getItem('themeSettings');
    if (savedThemeSettings) {
      Object.assign(themeSettings, JSON.parse(savedThemeSettings));
    }
    
    const savedNotificationSettings = localStorage.getItem('notificationSettings');
    if (savedNotificationSettings) {
      Object.assign(notificationSettings, JSON.parse(savedNotificationSettings));
    }
    
    const savedDisplaySettings = localStorage.getItem('displaySettings');
    if (savedDisplaySettings) {
      Object.assign(displaySettings, JSON.parse(savedDisplaySettings));
    }
  } catch (error) {
    console.error('加载用户设置失败', error);
  }
};

// 组件挂载时初始化
onMounted(async () => {
  loading.userInfo = true;
  try {
    // 使用store方法获取用户信息
    await userStore.fetchUserInfo();
    initUserForm();
    loadUserSettings();
  } catch (error) {
    console.error('获取用户信息失败', error);
    ElMessage.error('获取用户信息失败');
  } finally {
    loading.userInfo = false;
  }
});
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.page-title .el-icon {
  margin-right: 8px;
  font-size: 24px;
  color: var(--primary-color);
}

.user-card {
  margin-bottom: 20px;
  text-align: center;
}

.user-card-header {
  padding: 20px 0;
}

.avatar-container {
  position: relative;
  display: inline-block;
  margin-bottom: 15px;
}

.avatar-upload {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: var(--primary-color);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: white;
  transition: all 0.3s;
}

.avatar-upload:hover {
  transform: scale(1.1);
}

.edit-icon {
  font-size: 14px;
}

.user-name {
  margin: 10px 0 5px;
  font-size: 20px;
  font-weight: bold;
}

.user-role {
  color: var(--el-text-color-secondary);
  margin-bottom: 15px;
}

.user-card-content {
  padding: 0 15px 20px;
}

.user-info-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  color: var(--el-text-color-regular);
  text-align: left;
}

.user-info-item .el-icon {
  margin-right: 10px;
  font-size: 16px;
  flex-shrink: 0;
}

.user-info-item span {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.user-card-footer {
  border-top: 1px solid var(--el-border-color-lighter);
  padding-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 20px 15px;
}

@media (max-width: 768px) {
  .el-col {
    margin-bottom: 20px;
  }
}
</style> 